<?php

namespace Modules\User\Services;

use Mockery\Undefined;
use EasyWeChat\Factory;
use Modules\User\Entities\User;
use Modules\User\Entities\UserWechat;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class WechatService
{
  private $miniProgram;

  public function __construct()
  {
    // 初始化小程序
    $this->miniProgram = app('wechat.mini_program');
    // $config = config('wechat.mini_program.default');
    // $this->miniProgram = Factory::miniProgram($config);;
  }

  // 微信API token登录
  public function login($params)
  {
    // 微信登录
    $session = $this->miniProgram->auth->session($params['code']);

    // 微信登录失败
    if (!$session) return null;

    // 整理参数
    // TODO:
    $params = [
      'openid' => $session['openid'],
      'appid' => $this->appid(),
      'nickname' => empty($params['nickName']) ? NULL : $params['nickName'],
      'avatar' => empty($params['avatarUrl']) ? NULL : $params['avatarUrl'],
      'gender' => empty($params['gender']) ? 0 : $params['gender'],
      'city' => empty($params['city']) ? NULL : $params['city'],
      'province' => empty($params['province']) ? NULL : $params['province'],
      'country' => empty($params['country']) ? NULL : $params['country'],
    ];

    // 刷新 token
    $wechat = $this->getOrCreate($params);
    $token = $this->refreshToken($wechat);

    return $token;
  }

  // 获取用户信息没有时会创建
  public function getOrCreate($p)
  {
    // 获取UserWechat
    $wechat = $this->getUser($p);

    if ($wechat) {
      // 补充用户信息
      $this->fillUserInfo($wechat, $p);
    } else {
      $wechat = $this->createUser($p)->first();
    }

    return $wechat;
  }

  // 补充用户信息
  protected function fillUserInfo(UserWechat $wechat, $p)
  {
    if (empty($p['nickname'])) return;

    $user = $wechat->user()->first();
    if ($user->nickname) return;

    $user->update($p);
  }

  // 获取微信用户信息
  public function getUser($p)
  {
    try {
      // 根据 openid 和 appid 获取
      if (!empty($p['openid']) && !empty($p['appid']))
        return UserWechat::where(['openid' => $p['openid'], 'appid' => $p['appid']])->firstOrFail();

      // 根据 unionid 获取
      if (!empty($p['unionid']))
        return UserWechat::where(['unionid' => $p['unionid']])->firstOrFail();

      // 根据 openid 获取
      if (!empty($p['openid']))
        return UserWechat::where(['openid' => $p['openid']])->firstOrFail();
    } catch (ModelNotFoundException $ex) {
      return null;
    }
    return null;
  }

  // 创建用户信息，并返回对应的微信用户。
  public function createUser($params)
  {
    $user = User::create($params);
    $wechat = $user->wechat()->create($params)->first();

    return $wechat;
  }

  // 获取小程序appid
  public function appid()
  {
    return config('wechat.mini_program.default.app_id');
  }

  // 刷新 api_token
  protected function refreshToken(UserWechat $wechat)
  {
    // 生成唯一的 token 码
    $token = session_create_id('');

    // 更新 api_key
    $wechat->api_token = $token;
    $wechat->save();

    return $token;
  }
}
